<template>
  <div class="MKT-CategoryManage-container">
    <category-header
      :headerForm="d.headerForm"
      @loadData="headerLoadData"
      @clear="headerClear"
    ></category-header>
    <div class="content-container">
      <XmCardHeader>
        <template v-slot:select>
          <el-radio-group
            v-model="d.search.status"
            style="margin-bottom: 30px"
            @change="loadData"
          >
            <el-radio-button :label="null">全部</el-radio-button>
            <el-radio-button :label="1">在店铺显示</el-radio-button>
            <el-radio-button :label="0">在店铺隐藏</el-radio-button>
          </el-radio-group>
        </template>
        <template v-slot:right>
          <el-button type="primary" @click="addType">新建分类</el-button>
        </template>
      </XmCardHeader>

      <div style="margin-bottom: 10px; margin-left: 12px">
        <!-- <el-checkbox v-model="d.search.allChecked"></el-checkbox> -->
        <!-- 当页全选  -->
        已选{{ selArrays?.length }}项，批量设置
        <el-button type="danger" @click="showFuncHub(5)">删除</el-button>
      </div>
      <PaginationTable
        ref="ptable"
        :tableData="d.listData"
        @pagination="paginaChange"
        :getPTbale="paginationTableRef"
        @cellSelectChange="cellSelectChange"
      >
        <el-table-column type="selection" width="55" />
        <XMTableColumn label="分类ID" prop="id" width="100"></XMTableColumn>
        <XMTableColumn
          :label="pageWithMKT ? '营销分类' : '商品分类'"
          prop="title"
          width="200"
        >
          <template #default="scope">
            <div class="cell-img">
              <ImageView v-model="scope.row.images"></ImageView>
              <el-popover
                placement="top-start"
                :width="200"
                trigger="hover"
                title="分类名"
                :content="scope.row.name"
              >
                <template #reference>
                  <span>{{ scope.row.name }}</span>
                </template>
              </el-popover>
            </div>
          </template>
        </XMTableColumn>
        <XMTableColumn label="排序">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              :icon="Top"
              @click="shopUpOnceSort(1, scope.row, scope.$index)"
            />
            <el-button
              type="primary"
              size="small"
              :icon="Bottom"
              @click="shopUpOnceSort(2, scope.row, scope.$index)"
            />
            <el-button
              type="warning"
              size="small"
              :icon="Download"
              style="transform: rotate(180deg)"
              @click="shopUpTopSort(scope.row, scope.$index)"
            />
          </template>
        </XMTableColumn>
        <XMTableColumn label="创建时间" prop="createTime"></XMTableColumn>
        <XMTableColumn label="状态" prop="status">
          <template #default="scope">
            {{ scope.row.status === 1 ? '显示' : '隐藏' }}
          </template>
        </XMTableColumn>
        <!-- <XMTableColumn label="商品编码" prop="goodsCode"></XMTableColumn> -->

        <XMTableColumn label="操作" width="350">
          <template #default="scope">
            <el-button
              size="small"
              text
              type="primary"
              @click="edit(scope.row, 3)"
            >
              修改
            </el-button>
            <el-button
              size="small"
              text
              type="primary"
              @click="edit(scope.row, 1)"
            >
              更改状态
            </el-button>
            <!--            <el-button-->
            <!--              size="small"-->
            <!--              text-->
            <!--              type="primary"-->
            <!--              @click="edit(scope.row, 2)"-->
            <!--            >-->
            <!--              分享-->
            <!--            </el-button>-->

            <el-button
              size="small"
              text
              type="danger"
              @click="edit(scope.row, 4)"
            >
              删除分类
            </el-button>
          </template>
        </XMTableColumn>
      </PaginationTable>
    </div>
    <add-category-dialog
      ref="addCategoryRef"
      :pageWithMKT="pageWithMKT"
      :cateGoryObject="cateGoryObject"
      @addSuccess="loadData"
    ></add-category-dialog>
  </div>
</template>
<script lang="ts" setup>
  import categoryHeader from '../../components/categoryHeader/index.vue'
  import addCategoryDialog from '../../components/addCategoryDialog/index.vue'
  import {
    getSalesItem,
    unsaleableType,
    UpOnceSortWithGooods,
    UpOnceSortWithSales,
    UpTopSortWithGoods,
    UpTopSortWithSales,
  } from '@/api/modules/shop'
  import { XmCardHeader } from '@/components/XMC'
  import {
    getSaleTypes,
    setSaleStatus,
    deleteSaleType,
    getGoodsTypes,
    setGoodStatus,
    deleteShopType,
  } from '@/api/modules/shop'
  import { reactive, ref, computed } from 'vue'
  import common from '@/utils/common'
  import { usePromise } from '@/hooks/core/usePromise.js'
  import { Top, Bottom, Download } from '@element-plus/icons-vue'
  import { useStops, useTableSort } from '../../hooks/useShops'
  import { useRoute } from 'vue-router'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import ImageView from '@/components/ImageView/index.vue'

  const { to } = usePromise()
  const cateGoryObject = ref()
  // const { salesStatusDic } = useStops()

  // init-view
  const d = reactive({
    search: { allChecked: false, pageIndex: 1, pageSize: 5, status: null },
    listData: { data: [] },
    headerForm: {},
  })
  const route = useRoute()
  const pageWithMKT = computed(() => {
    return route.name === 'MKT' ? true : false
  })

  async function loadData() {
    common.XmLoading(true)
    const [err, res] = pageWithMKT.value
      ? await to(getSaleTypes({ ...d.search, ...d.headerForm } as any))
      : await to(getGoodsTypes({ ...d.search, ...d.headerForm } as any))

    common.XmLoading(false)
    if (!err) {
      res.data.forEach((item: any) => {
        item.images = [{ url: item.imgUrl }]
      })
      d.listData = res
    }
    console.log('listData =' + JSON.stringify(d.listData))
  }

  // target-action
  // header
  function headerLoadData(search: getSalesItem) {
    loadData()
  }

  const ptable = ref()
  function headerClear() {
    d.headerForm = {}
    d.search.allChecked = false
    d.search.pageIndex = 1
    d.search.pageSize = 5

    ptable.value.clearData()
    loadData()
  }

  // 弹窗
  const addCategoryRef = ref()
  function addType() {
    addCategoryRef.value.initForm()
  }

  onMountedOrActivated(() => {
    loadData()
  })
  // table 方法
  // 选中或取消的
  const selArrays = ref<Partial<getSalesItem[]>>()
  function cellSelectChange(selection: getSalesItem[]) {
    selArrays.value = selection
  }

  const paginationTableRef = ref()
  function paginaChange(params: any) {
    d.search.pageIndex = params.current
    d.search.pageSize = params.pageSize
    loadData()
  }

  function shopUpOnceSort(type: number, item: any, index: number) {
    // @ts-ignore
    if (index + 1 >= d.listData.total && type === 2) {
      common.XmAlert('已经是最底层')
      return
    } else if (index === 0 && type === 1) {
      common.XmAlert('已经到顶')
      return
    }
    const data = { ...d.search, ...d.headerForm }
    const table = d.listData.data
    useTableSort(
      data,
      item,
      type === 1 ? true : false,
      table,
      pageWithMKT.value ? UpOnceSortWithSales : UpOnceSortWithGooods,
      pageWithMKT.value ? getSaleTypes : getGoodsTypes,
      () => {
        // console.log('排序成功')
        // msg
        loadData()
      }
    )
  }

  // 商品和分类置顶
  async function shopUpTopSort(row: any, index: number) {
    if (index === 0) {
      common.XmAlert('已经到顶')
      return
    }
    // await common.syncAlert('是否将该商品置顶')
    await common.syncAlert(
      `是否将该${pageWithMKT.value ? '营销分类' : '商品分类'}置顶`
    )
    common.XmLoading(true)
    const [err, res] = pageWithMKT.value
      ? await to(UpTopSortWithSales({ oid: row.id }))
      : await to(UpTopSortWithGoods({ oid: row.id }))
    common.XmLoading(false)
    if (!err) {
      loadData()
    }
  }

  // edit
  async function edit(item: getSalesItem, type: number) {
    switch (type) {
      case 1:
        {
          // 修改状态
          await common.syncAlert(
            `是否确认修改${pageWithMKT.value ? '营销分类' : '商品分类'}状态`
          )
          const [err, res] = pageWithMKT.value
            ? await to(setSaleStatus({ id: item.id }))
            : await to(setGoodStatus({ id: item.id }))
          if (!err) {
            common.XmMessage(0, '修改成功')
            loadData()
          }
        }
        break
      case 2:
        break
      case 3:
        {
          addCategoryRef.value.initForm(item)
        }
        break
      case 4:
        {
          // 删除
          await common.syncAlert(
            `是否确认删除 ${pageWithMKT.value ? '营销分类' : '商品分类'}：${
              item.name
            }`
          )
          const [err, res] = pageWithMKT.value
            ? await to(deleteSaleType([{ itemId: item.id }]))
            : await to(deleteShopType([{ itemId: item.id }]))
          if (!err) {
            common.XmMessage(0, '删除成功')
            loadData()
          }
        }
        break
      default:
        break
    }
  }

  async function showFuncHub(type: number) {
    if (selArrays.value?.length === 0) {
      common.XmMessage(1, '至少选择一项')
    }
    let data: unsaleableType[] = []

    if (selArrays.value) {
      data = selArrays.value.map((item: any) => {
        return { itemId: item.id }
      })
    }
    const [err, res] = pageWithMKT.value
      ? await to(deleteSaleType(data))
      : await to(deleteShopType(data))
    if (!err) {
      common.XmMessage(0, '批量删除成功')
      loadData()
    }
  }
</script>
<style lang="scss" scoped>
  @import '@/styles/mixin.scss';
  .MKT-CategoryManage-container {
    margin: 22px;

    .content-container {
      @include card-shadow;
      margin-top: 22px;
      background-color: white;
      padding: 11px;
      :deep(.el-radio-group) {
        margin-bottom: 10px !important;
      }
      .add-medicine {
        margin: 12px;
      }
      .cell-img {
        display: flex;
        .imageView-container {
          width: 80px;
          height: 80px;
          border-radius: 5px;
        }
        span {
          margin-left: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
      }

      .shop-table-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
</style>
